<script setup>
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Edit } from '@element-plus/icons-vue'
import { changePasswordAPI } from '@/apis/user'
import { modifyUserInfoAPI } from '@/apis/user'
import { getAddressAPI, changeDefaultAddressAPI } from '@/apis/addressBook'
import { getUserInfoAPI } from '@/apis/user'
import { useUserStore } from '@/stores/usersStore'

// 个人信息表单数据
const form = ref({})
//获取个人信息
const getUserInfo = async () => {
    form.value = (await getUserInfoAPI()).data
    if (form.value.avatar != null && form.value.avatar != '') {
        avatar.value = form.value.avatar
    }
}
onMounted(() => getUserInfo())
// 修改密码表单数据
const passwordForm = ref({
    oldPassword: '',
    newPassword: '',
    rePassword: ''
})

// 表单验证规则
const rules = ref({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
    ],
    phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
    ],
    email: [
        { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
    ]
})

// 密码验证规则
const passwordRules = ref({
    oldPassword: [
        { required: true, message: '请输入旧密码', trigger: 'blur' }
    ],
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 14, message: '密码长度为6到14个字符', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                // 同时包含数字和字母的正则表达式
                const hasNumber = /\d/;
                const hasLetter = /[a-zA-Z]/;

                if (!hasNumber.test(value) || !hasLetter.test(value)) {
                    callback(new Error('密码必须包含数字和字母'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ],
    rePassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        { min: 6, max: 14, message: '密码长度为6到14个字符', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value != passwordForm.value.newPassword) {
                    callback(new Error('两次输入的密码不一致'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ]
})
const toggleEditMode = () => {
    editMode.value = true
}
const editMode = ref(false)
const passwordDialogVisible = ref(false)
const formRef = ref(null)
const passwordFormRef = ref(null)

// 显示修改密码对话框
const showChangePasswordDialog = () => {
    passwordDialogVisible.value = true
    // 重置表单
    if (passwordFormRef.value) {
        passwordFormRef.value.resetFields()
    }
}

// 提交密码修改
const submitPasswordChange = async () => {
    await passwordFormRef.value.validate()
    // 这里调用修改密码的API
    await changePasswordAPI(passwordForm.value)
    ElMessage.success('密码修改成功')
    passwordDialogVisible.value = false
}
//修改用户信息
const saveProfile = async () => {
    form.value = (await modifyUserInfoAPI(form.value)).data
    ElMessage({ type: 'success', message: '修改成功！' })
    editMode.value = false
}
const cancelEdit = () => {
    editMode.value = false
}
const avatar = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')
// 头像上传处理
const userStore = useUserStore()
const action = '/api/user/upload'
const headers = {
    Authorization: 'Bearer ' + userStore.userInfo.token
}
const beforeAvatarUpload = (file) => {
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isImage) {
        ElMessage.error('只能上传图片文件!')
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过2MB!')
    }
    return isImage && isLt2M
}
const handleAvatarSuccess = (respose) => {
    avatar.value = respose.data
    form.value.avatar = respose.data
}
//收货地址
const addressList = ref([])
const getAddress = async () => {
    addressList.value = (await getAddressAPI()).data
}
onMounted(() => getAddress())
const selectedAddressId = ref('')
const changeDefaultAddress = async () => {
    if (selectedAddressId.value == '') {
        ElMessage({ type: 'warning', message: '请选择地址！' })
        return
    }
    await changeDefaultAddressAPI(selectedAddressId.value)
    ElMessage({ type: 'success', message: '修改成功！' })
    getAddress()
}

</script>
<template>
    <div class="user-profile-container">
        <el-card class="profile-card">
            <template #header>
                <div class="card-header">
                    <span>个人信息</span>
                    <div>
                        <el-button type="primary" @click="toggleEditMode" v-if="!editMode">
                            编辑
                        </el-button>
                        <el-button type="warning" @click="showChangePasswordDialog" v-if="!editMode">
                            修改密码
                        </el-button>
                        <div v-else>
                            <el-button type="success" @click="saveProfile">保存</el-button>
                            <el-button @click="cancelEdit">取消</el-button>
                        </div>
                    </div>
                </div>
            </template>

            <!-- 个人信息内容 -->
            <div class="profile-content">
                <!-- 头像上传 -->
                <div class="avatar-section">
                    <el-upload class="avatar-uploader" :action="action" :headers="headers" :show-file-list="false"
                        :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess" :disabled="!editMode">
                        <el-avatar :size="100" :src="avatar" class="avatar" />
                        <div class="avatar-edit" v-if="editMode">
                            <el-icon>
                                <Edit />
                            </el-icon>
                        </div>
                    </el-upload>
                </div>

                <!-- 个人信息表单 -->
                <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-position="left">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="form.username" disabled />
                    </el-form-item>

                    <el-form-item label="个性签名" prop="signature">
                        <el-input v-model="form.signature" :disabled="!editMode" type="textarea"
                            :autosize="{ minRows: 2 }" placeholder="你似乎还没有个性签名" />
                    </el-form-item>

                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="form.phone" :disabled="!editMode" />
                    </el-form-item>

                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="form.email" :disabled="!editMode" />
                    </el-form-item>
                    <el-form-item label="默认收货地址">
                        <el-select v-model="selectedAddressId" placeholder="请选择默认收获地址" style="width: 380px"
                            :disabled="!editMode">
                            <el-option v-for="item in addressList" :key="item.id" :label="item.fullAddress"
                                :value="item.id" />
                        </el-select>
                        <el-button type="primary" @click="changeDefaultAddress">确认切换</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-card>

        <!-- 修改密码对话框 -->
        <el-dialog v-model="passwordDialogVisible" title="修改密码" width="400px" :close-on-click-modal="false">
            <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="100px">
                <el-form-item label="旧密码" prop="oldPassword">
                    <el-input v-model="passwordForm.oldPassword" type="password" show-password placeholder="请输入旧密码" />
                </el-form-item>

                <el-form-item label="新密码" prop="newPassword">
                    <el-input v-model="passwordForm.newPassword" type="password" show-password placeholder="请输入新密码" />
                </el-form-item>

                <el-form-item label="确认密码" prop="rePassword">
                    <el-input v-model="passwordForm.rePassword" type="password" show-password placeholder="请再次输入新密码" />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="passwordDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitPasswordChange">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<style lang="scss" scoped>
.user-profile-container {
    max-width: 800px;
    margin: 20px auto;

    .profile-card {
        border-radius: 8px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 20px;

            span {
                font-size: 18px;
                font-weight: 500;
            }
        }

        .profile-content {
            display: flex;
            gap: 30px;
            padding: 20px;

            .avatar-section {
                flex-shrink: 0;
                position: relative;

                .avatar-uploader {
                    position: relative;
                    cursor: pointer;

                    .avatar {
                        border: 2px solid #eee;
                        transition: border-color 0.3s ease;

                        &:hover {
                            border-color: var(--el-color-primary);
                        }
                    }

                    .avatar-edit {
                        position: absolute;
                        right: 5px;
                        bottom: 5px;
                        background: rgba(0, 0, 0, 0.5);
                        color: white;
                        padding: 5px;
                        border-radius: 50%;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        transition: opacity 0.3s;

                        .el-icon {
                            font-size: 14px;
                        }
                    }
                }
            }

            ::v-deep(.el-form) {
                flex: 1;

                .el-form-item {
                    margin-bottom: 18px;

                    &__label {
                        color: #666;
                    }

                    .el-input,
                    .el-textarea {
                        &__inner {
                            transition: all 0.3s;

                            &:disabled {
                                background-color: #fafafa;
                                border-color: #eee;
                                color: #666;
                            }
                        }
                    }
                }
            }
        }
    }
}

@media (max-width: 768px) {
    .user-profile-container {
        margin: 10px;

        .profile-content {
            flex-direction: column;
            gap: 20px;

            .avatar-section {
                align-self: center;
            }
        }
    }
}
</style>